package com.nbjtjc.safe.service.sys;

import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysUserRoleMapper;
import com.nbjtjc.safe.model.sys.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
public class SysUserRoleService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Transactional(rollbackFor = {Throwable.class})
    public Result add(int[] roleIds, int userId){
        Result result=new Result();
        try {
            if(userId==0){
                result.setFalse();
                return result;
            }
            sysUserRoleMapper.deleteByUserId(userId);
            ArrayList<SysUserRole> userRoles=new ArrayList<>();
            if(roleIds!=null&&roleIds.length>0){
                for (int i=0;i<roleIds.length;i++){
                    SysUserRole userRole=new SysUserRole(roleIds[i],userId);
                    userRoles.add(userRole);
                }
                sysUserRoleMapper.insertList(userRoles);
                result.setData(userRoles);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
    @Transactional(rollbackFor = {Throwable.class})
    public Result delete(int userRoleId){
        Result result=new Result();
        try {
            sysUserRoleMapper.deleteByPrimaryKey(userRoleId);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
}
